package thread;

/**
 * @Author liangzai
 * @Description:
 */

class MyBlockQeueu{
    private int head = 0;
    private int tile = 0;

    private int size = 0;
    private int[] data = null;

    public MyBlockQeueu(int n){
        data = new int[n];
    }

    public void put(int val){
        synchronized (this) {
            try{
                while (size >= data.length) {
                    this.wait();
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            data[tile++] = val;
            if (tile >= data.length) {
                tile = 0;
            }
            size++;
            this.notify();
        }
    }

    public int take(){
        synchronized (this){
            try {
                while (size == 0) {
                    this.wait();
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            int ret = data[head++];
            if (head >= data.length) {
                head = 0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}

public class Demo5 {
    public static void main(String[] args) {
        MyBlockQeueu qeueu = new MyBlockQeueu(10);
        Thread producer = new Thread(()->{
            for (int i = 0; i <= 100; i++) {
                qeueu.put(i);
                System.out.println("生产元素:"+i);
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
        },"producer");
        Thread consumer = new Thread(()->{
            while(true){
                int key = qeueu.take();
                System.out.println("消费元素:"+key);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"consumer");

        producer.start();
        consumer.start();
    }
}
